/**相关的接口 */
const express = require("express");
const router = express.Router();
const Joi = require("joi");
const Response = require("../utils/Response.js");

// 引入mysql连接池
const pool = require("../utils/db.js");

router.post("/commodity/select", (req, resp) => {
  let { jieshao } = req.body;
 //TODO 服务端表单验证  如果验证通过那么继续后续业务  如果验证不通过，则直接返回参数异常
 let schema = Joi.object({
    jieshao: Joi.string().required(), // 必填
  });
  let { error, value } = schema.validate(req.body);
  if (error) {
    resp.send(Response.error(400, error));
    return; // 结束
  }  
  // 执行模糊查询
  let sql = "select * from commodity where jieshao like ? ";
  pool.query(sql, [`%${jieshao}%`], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    // 将结果封装，返回给客户端
    resp.send(Response.ok(result));
  });
});




/**
 * 删除业务
 */
router.post("/commodity/delete", (req, resp) => {
  let { id } = req.body;
  // 执行删除业务
  let sql = "delete from commodity where id = ?";
  pool.query(sql, [id], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    resp.send(Response.ok());
  });
});




/**
 *添加商品列表
 */
 router.post("/commodity/add", (req, resp) => {
  let {
    id,
    photo,
    price,
    jieshao,
    duanju ,
  } = req.body; // post请求参数在req.body中
  // 表单验证
  let schema = Joi.object({
    id: Joi.string().required(),
    photo: Joi.string().required(),
    price: Joi.string().required(),
    jieshao: Joi.string().required(),
    duanju: Joi.string().required(),
  });
  let { error, value } = schema.validate(req.body);
  if (error) {
    resp.send(Response.error(400, error));
    return; // 结束
  }
  let sql = `insert into commodity (
    id,
    photo,
    price,
    jieshao,
    duanju
    ) value (?,?,?,?,?)`;
    /***
     * 执行增加商品
     */
pool.query(
  sql,
  [id,photo,price,jieshao,duanju],
  (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    resp.send(Response.ok());
  }
);
});




/***
 * 购物车
 */
// 将router对象导出
module.exports = router;
